
class ListNode {
  int val;
  ListNode next = null;

  ListNode(int val) {
    this.val = val;
  }
}

public class Solution {
  public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if(headA == null|| headB==null){
      return null;
    }
    ListNode temp1 = headA;
    int i1 = 0;
    while (temp1 != null) {
      i1++;
      temp1 = temp1.next;
    }
    ListNode temp2 = headB;
    int i2 = 0;
    while (temp2 != null) {
      i2++;
      temp2 = temp2.next;
    }
    int step = i1 - i2;
    temp1 = headA;
    temp2 = headB;
    if (step > 0) {
      while (step > 0) {
        temp1 = temp1.next;
        step--;
      }
    } else {
      while (step < 0) {
        temp2 = temp2.next;
        step++;
      }
    }
    while (temp1 != null) {
      if (temp1 == temp2) {
        return temp1;
      }
      temp1 = temp1.next;
      temp2 = temp2.next;
    }
    return null;
  }
}